package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-master/cache"
	"pet-master/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var pet []models.Pet
	redis_key := "pet_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("pets").Offset(offset).Limit(size).Find(&pet)
		jsonData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}

	var count int64
	models.DB.Model(&models.Pet{}).Count(&count)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"pet":   pet,
		},
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var pet models.Pet
	redis_key := "pet_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&pet)
		jsonData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": pet,
	})
	return

}
